#!/usr/bin/python2.4
#
# rpc utility functions and some convenient wrappers.


import pprint
import time

import common
from autotest_lib.cli import rpc

from logger import rpc_logger


AUTOTEST_WEB = rpc.get_autotest_server()
if AUTOTEST_WEB.lower().startswith('http://'):
  AUTOTEST_WEB = AUTOTEST_WEB[7:].rstrip('/')


_afe = rpc.afe_comm()
_tko = rpc.tko_comm()


class _LogRpcCall(object):

  def __init__(self, rpc, name='rpc'):
    self.rpc = rpc
    self.name = name

  def __getattr__(self, name):

    def run_wrapper(*args, **dargs):
      dargs.setdefault('caller_level', 5)
      return self.run(name, *args, **dargs)

    if name.startswith('_'):
      raise AttributeError('%r object has no attribute %r' %
                           (self.name, name))
    return run_wrapper

  def run(self, op, *args, **dargs):
    log_results = dargs.pop('log_results', True)
    caller_level = dargs.pop('caller_level', 4)
    args_list = ([repr(arg) for arg in args] +
                 ['%s=%r' % (key, value) for key, value in dargs.iteritems()])
    rpc_logger.debug('RPC %s.%s(%s)' % (self.name, op, ', '.join(args_list)),
                     caller_level=caller_level)
    start_time = time.time()
    results = self.rpc.run(op, *args, **dargs)
    rpc_finish_time = time.time()
    if log_results:
      rpc_logger.debug(pprint.pformat(results), caller_level=caller_level)
    else:
      rpc_logger.debug('Results is not logged', caller_level=caller_level)
    log_finish_time = time.time()
    rpc_logger.debug('RPC done in %.2g seconds, logging done in %.2g seconds' %
                     (rpc_finish_time - start_time,
                      log_finish_time - rpc_finish_time),
                     caller_level=caller_level)
    return results


afe = _LogRpcCall(_afe, name='afe')
tko = _LogRpcCall(_tko, name='tko')
